from HrefDataCatcher import HrefDataCatcher
from fiction.models import Fiction, Chapter
import urllib
from django.http import HttpResponse
from django.template import Context, loader

def renew(request):
    fiction_list = Fiction.objects.all()
    for t_fiction in fiction_list:
        mounts = t_fiction.chapter_set.count() - 1
        usock = urllib.urlopen(t_fiction.url)
        parser = HrefDataCatcher()
        parser.feed(usock.read().decode('gbk'))
        parser.close()
        usock.close()
        for row in parser.data[mounts:]:
            t_fiction.chapter_set.create(chapter = row)
    return HttpResponse("It's done!")

def test(request):
    p = Fiction.objects.all()
    c = []
    b = 0
    for x in p:
        a = x.chapter_set.all()
        count = a.count() - 3
        c.append(a[count : ])
        b = b + 1
    t = loader.get_template('story.html')
    d = Context({
            'q': c,
            })
    return HttpResponse(t.render(d))
